﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Configuration;
using Microsoft.Extensions.Configuration;
using YougeBookmark.Models;

namespace YougeBookmark.DataAccess;

/// <summary>
/// 数据库初始化工具类
/// </summary>
public static class DatabaseInitializer
{
    private static readonly ILoggerFactory ConsoleLoggerFactory = LoggerFactory.Create(builder =>
    {
        builder.AddFilter((category, level) =>
            category == DbLoggerCategory.Database.Command.Name && level >= LogLevel.Information)
        .AddConsole();
    });

    /// <summary>
    /// 初始化数据库并创建默认数据
    /// </summary>
    public static void Initialize()
    {
        try
        {
            // 从配置中获取连接字符串
            var connectionString = Program.ConnectionString;//configuration.GetConnectionString("SQLite");

            var options = new DbContextOptionsBuilder<AppDbContext>()
                .UseSqlite(connectionString)
                .Options;
            using var context = new AppDbContext(options);
            //using var context = new AppDbContext();

            // 自动创建数据库和表结构
            context.Database.EnsureCreated();

            // 添加默认标签（如果不存在）
            SeedDefaultTags(context);
        }
        catch (Exception ex)
        {
            // 处理初始化错误
            throw new InvalidOperationException("数据库初始化失败", ex);
        }
    }

    //public static void Initialize()
    //{
    //    try
    //    {
    //        // 从配置中获取连接字符串
    //        var connectionString = Program.ConnectionString;//configuration.GetConnectionString("SQLite");

    //        var options = new DbContextOptionsBuilder<AppDbContext>()
    //            .UseSqlite(connectionString)
    //            .Options;

    //        using var context = new AppDbContext(options);

    //        // 应用迁移，确保数据库表结构已创建
    //        context.Database.Migrate();

    //        // 添加默认标签（如果不存在）
    //        SeedDefaultTags(context);
    //    }
    //    catch (Exception ex)
    //    {
    //        // 处理初始化错误
    //        throw new InvalidOperationException("数据库初始化失败", ex);
    //    }
    //}

    /// <summary>
    /// 填充默认标签数据
    /// </summary>
    private static void SeedDefaultTags(AppDbContext context)
    {
        if (!context.Tags.Any())
        {
            var defaultTags = new[]
            {
                new Tag { Name = "时政", ColorCode = "#FF5722" },
                new Tag { Name = "财经", ColorCode = "#4CAF50" },
                new Tag { Name = "军事", ColorCode = "#2196F3" },
                new Tag { Name = "科技", ColorCode = "#9C27B0" },
                new Tag { Name = "行业", ColorCode = "#FFC107" }
            };

            context.Tags.AddRange(defaultTags);
            context.SaveChanges();
        }
    }

    /// <summary>
    /// 启用EF Core日志（调试用）
    /// </summary>
    public static void EnableDebugLogging()
    {
        using var context = new AppDbContext();
        context.Database.SetCommandTimeout(60);
        context.Database.EnsureCreated();
    }
}